package dao

import (
	"context"
	"gorm.io/gorm"
	"mall-admin-go/model"
	"strconv"
	"strings"
)

type CategoriesDao struct {
	*gorm.DB
}

func NewCategoriesDao(ctx context.Context) *CategoriesDao {
	return &CategoriesDao{NewDBCliet(ctx)}
}

// ListCategories 获取全部分类
func (dao *CategoriesDao) ListCategories() (categories []*model.Categories, err error) {
	err = dao.DB.Model(&model.Categories{}).Find(&categories).Error
	return categories, err
}

// GetCategoriesByName 根据名称查询单个分类
func (dao *CategoriesDao) GetCategoriesByName(name string) bool {
	err := dao.DB.Model(&model.Categories{}).Where("name = ?", name).Error
	if err != nil {
		return false
	}
	return true
}

// GetCategoriesByPid 根据id查询分类
func (dao *CategoriesDao) GetCategoriesByPid(pid string) (categories []*model.Categories, err error) {
	pidLen := strings.Split(pid, ",")
	//只有一个参数并且=10000 查询所有一级分类
	if len(pidLen) == 1 && pidLen[0] == "10000" {
		err = dao.DB.Model(&model.Categories{}).Where("parent_id=?", 0).Find(&categories).Error
		return
	}
	//多级查询
	if len(pidLen) == 1 && pidLen[0] != "10000" {
		parentId, _ := strconv.ParseUint(pidLen[0], 10, 64)
		err = dao.DB.Model(&model.Categories{}).Where("parent_id=?", parentId).Find(&categories).Error
		return
	}
	//条件为空查询所有分类
	err = dao.DB.Model(&model.Categories{}).Find(&categories).Error
	return categories, err
}

// Create 添加分类
func (dao *CategoriesDao) Create(pid, name, img string) (err error) {

	//if dao.GetCategoriesByName(name) {
	//	return errors.New("分类名称已存在")
	//}

	pidLen := strings.Split(pid, ",")
	categories := model.Categories{}
	//图片不为空 三级分类
	if img != "" {
		ParentId, _ := strconv.ParseUint(pidLen[0], 10, 64)
		categories.Img = img
		categories.Name = name
		categories.ParentId = uint(ParentId)
		err = dao.DB.Model(&model.Categories{}).Create(&categories).Error
		return
	}
	//图片为空 pid不为空 二级分类
	if len(pidLen) == 1 && img == "" {
		ParentId, _ := strconv.ParseUint(pidLen[0], 10, 64)
		categories.Img = img
		categories.Name = name
		categories.ParentId = uint(ParentId)
		err = dao.DB.Model(&model.Categories{}).Create(&categories).Error
		return
	}
	//一级分类
	if pid == "" && img == "" {
		categories.Name = name
		err = dao.DB.Model(&model.Categories{}).Create(&categories).Error
		return
	}
	return
}
